import { Button, message, Modal } from "antd";
import { PropsWithChildren, useEffect, useRef, useState } from "react";
import { ChatPanel } from "./ChatPanel";
import {
  fetchCreateChat,
  fetchGetChatInfo,
  getUserId,
} from "@/api/server/recommend_question";
import { useSessionStorageState } from "ahooks";
import { randomNumber } from "@/utils";

interface IAffixedChatProps {
  className?: string;
}
export function AffixedChat(props: PropsWithChildren<IAffixedChatProps>) {
  const [chatOpen, setChatOpen] = useState(false);
  const [historyList, setHistoryList] = useState([]);
  const socketRef = useRef<WebSocket>();
  const [chatId, setChatId] = useSessionStorageState<string>(
    "webscoket_chat_id",
    {
      defaultValue: "",
    }
  );

  const onShowChatModal = () => {
    setChatOpen(true);
  };

  const initWebsocket = () => {
    const userId = getUserId();
    console.log("userId", userId);
    socketRef.current = new WebSocket(`ws://${location.host}/ws/${userId}`);

    // 当连接成功建立时触发
    socketRef.current.onopen = function (event) {
      console.log("WebSocket is open now.");
      // 连接建立后，你可以发送消息到服务器
      // socketRef.current.send("Hello Server!");
    };

    // 当从服务器接收到消息时触发
    socketRef.current.onmessage = function (event) {
      try {
        const data = JSON.parse(event.data);
        if (!data?.content?.reply) {
          return;
        }
        setHistoryList((list) => {
          return list.concat([
            {
              key: randomNumber(),
              role: "lawyer",
              text: data?.content?.reply,
            },
          ]);
        });
      } catch (err) {
        console.log("Message from server ", event.data);
      }
    };

    // 当连接关闭时触发
    socketRef.current.onclose = function (event) {
      if (event.wasClean) {
        console.log(
          "WebSocket connection closed cleanly, code=",
          event.code,
          " reason=",
          event.reason
        );
      } else {
        // e.g. server process killed or network down
        // event.code is usually 1006 in this case
        console.log("WebSocket connection died");
      }
    };

    // 当连接发生错误时触发
    socketRef.current.onerror = function (error) {
      console.log("WebSocket Error: ", error);
    };
  };

  const closeWebsocket = () => {
    socketRef.current?.close();
    socketRef.current = null;
  };

  const sendMsg = (s: string) => {
    socketRef.current.send(
      JSON.stringify({
        chat_id: chatId,
        sender: "user",
        message: s,
      })
    );
  };

  const initList = async () => {
    let chat_id = chatId;

    if (!chat_id) {
      const chatInfo = await fetchCreateChat({
        user_name: "test",
        sender: "user",
        message: "",
        type: "lawyer",
      });
      chat_id = chatInfo?.data?.chat_id;
      setChatId(chat_id);
    }

    const res = await fetchGetChatInfo({
      chat_id,
      search_type: "chat_id",
      type: "lawyer",
      user_id: getUserId(),
    });

    const list = res?.data?.chat_info?.messages;

    setHistoryList(
      list
        ?.filter((item) => !!item.message)
        .map((item) => {
          return {
            key: item.child_chat_id,
            role: item.sender,
            text: item.message,
          };
        })
    );
  };

  useEffect(() => {
    initWebsocket();
    initList();

    return () => {
      closeWebsocket();
    };
  }, []);

  return (
    <>
      <div className="fixed right-[32px] bottom-[32px]">
        <img src="/images/kefu.png" className="w-[120px]" />
        <div className="absolute bottom-[14px] left-0 w-[120px] flex flex-row justify-center">
          <Button onClick={onShowChatModal}>在线咨询</Button>
        </div>
      </div>
      <Modal
        open={chatOpen}
        footer={null}
        onCancel={() => setChatOpen(false)}
        title="在线咨询"
      >
        <ChatPanel
          defaultList={historyList}
          onSend={(msg) => {
            sendMsg(msg);
          }}
        />
      </Modal>
    </>
  );
}
